package com.ocean.web.controller.product;

import com.google.common.collect.ImmutableList;
import com.ocean.common.core.controller.BaseController;
import com.ocean.common.core.domain.AjaxResult;
import com.ocean.common.utils.YamlUtil;
import com.ocean.nc.domain.ONcFile;
import com.ocean.nc.service.IONcFileService;
import com.ocean.productDict.domain.OFrequency;
import com.ocean.productDict.domain.OZnwgSt;
import com.ocean.productDict.domain.oNcfileMonitor;
import com.ocean.productDict.service.IOFrequencyService;
import com.ocean.system.service.ISysConfigService;
import map.core.*;
import map.core.util.NcVariable;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import ucar.ma2.Array;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.Dimension;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dataset.NetcdfDatasets;
/*import ucar.ma2.Array;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;*/

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ocean.web.util.NcimgUtil.getColor;
import static com.ocean.web.util.NcimgUtil.rotate180;

/**
 * Leaflet地图Controller
 *
 * @author ocean
 * @date 2023-01-04
 */
@Controller
@RequestMapping("/leaflet/map")
public class LeafletMapController extends BaseController
{
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IOFrequencyService frequencyService;
    @Autowired
    private IONcFileService ncFileService;
    @Autowired
    private com.ocean.productDict.service.oNcfileMonitorService oNcfileMonitorService;
    private String prefix = "product/tomap";


    @RequiresPermissions("leaflet:map:view")
    @GetMapping()
    public String modePop(){
        return prefix + "/tomap";
    }
    @GetMapping("/yldt/{data}")
    public String ylmap(@PathVariable("data") String data, ModelMap mmap)
    {
        String[] split = data.split("&");
        String minLon = split[0];
        String maxLon = split[1];
        String minLat = split[2];
        String maxLat = split[3];
        mmap.addAttribute("zxx",minLon);
        mmap.addAttribute("ysx",maxLon);
        mmap.addAttribute("zxy",minLat);
        mmap.addAttribute("ysy",maxLat);
        return prefix + "/tomap";
    }
    @GetMapping("/fw/{minLon}/{maxLon}/{minLat}/{maxLat}")
    public String ylmap(@PathVariable("minLon") String minLon,@PathVariable("maxLon") String maxLon,@PathVariable("minLat") String minLat,@PathVariable("maxLat") String maxLat, ModelMap mmap)
    {
        mmap.addAttribute("zxx",minLon);
        mmap.addAttribute("ysx",maxLon);
        mmap.addAttribute("zxy",minLat);
        mmap.addAttribute("ysy",maxLat);
        return prefix + "/nccjfw";
    }
    @PostMapping("/getconfig")
    @ResponseBody
    public AjaxResult getconfig(String bm, String ljb){
        OZnwgSt st = oNcfileMonitorService.getst(bm, ljb);//获取省台名称
        return AjaxResult.success(st);
    }
    /**
     * 跳转到展示页面
     * @param file
     * @param mmap
     * @return fileName+ "/" +qbsj+ "/" +sjjg+ "/" +cpsjlx+ "/" +isjc,
     */
    @GetMapping("/yl/{fileName}/{qbsj}/{sjjg}/{cpsjlx}/{isjc}/{namep}")
    public String add(@PathVariable("fileName") String file,
                      @PathVariable("qbsj")String qbsj,
                      @PathVariable("sjjg")String sjjg,
                      @PathVariable("cpsjlx")String cpsjlx,
                      @PathVariable("isjc")String isjc,
                      @PathVariable("namep")String namep,
                      ModelMap mmap)
    {
        //判断是否为windows系统
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        String[] s = file.split("_");
        String filePath = "cloud/ocean"+"/"+s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3]+"/"+file;
        if(archive.equals("win")){
            filePath = "D:\\\\cloud\\\\ocean"+"\\\\"+s[0]+"\\\\"+s[1]+"\\\\"+s[2]+"\\\\"+s[3]+"\\\\"+file;
        }else{//判断是否为linux系统

            //filePath = "/cloud/ocean"+"/"+s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3]+"/"+file;//正式环境用这个从根目录读取
            String pDir = configService.selectConfigByKey("gdlinuxpathh");//普通产品归档后路径
            filePath = pDir+"/"+s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3]+"/"+file;//从项目当前目录读取
        }
        mmap.addAttribute("namep",namep);
        mmap.addAttribute("fileName",file);
        //获取起报时间和间隔时间
        mmap.addAttribute("filePath", filePath);
        if(sjjg.equals("no")){//判断时间间隔参数是否有值，没有值时间间隔按1进行设置
            mmap.addAttribute("sjjg",1);//默认时间间隔(小时)
        }else{
            mmap.addAttribute("sjjg",sjjg);//时间间隔
        }
        if(isjc.equals("no")){
            mmap.addAttribute("isjc",-9999);//去除数值 如果=no 就默认值-9999
        }else{
            mmap.addAttribute("isjc",isjc);//去除数值
        }

        String time = s[4];
        if(time.length()<12){//判断s[4]时间是否够12位 不够添0
            int i = 12 - time.length();
            for (int j = 0; j < i; j++) {
                time +="0";
            }
        }
        //获取文件时间
        String getybtime = getybtime(time);
        if(!getybtime.equals("-1")){
            if(qbsj.equals("no")) {//判断起报时间参数是否有值，没有值时间间隔按01进行设置
                // 调用方法替换小时并获取新的时间字符串
                if(cpsjlx.equals("1")){//判断cpsjlx 为0是世界时  未1是北京时,北京时要减去八小时
                    // 定义日期时间格式
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    // 解析字符串为LocalDateTime对象
                    LocalDateTime dateTime = LocalDateTime.parse(getybtime, formatter);
                    // 减去8小时
                    LocalDateTime newDateTime = dateTime.minus(Duration.ofHours(8));
                    // 输出新的日期时间
                    mmap.addAttribute("qbsj", newDateTime.format(formatter));//起报时间
                }else{
                    mmap.addAttribute("qbsj", getybtime);//起报时间
                }

            }else{
                OFrequency oFrequency = new OFrequency();
                oFrequency.setCode(qbsj);
                /*OFrequency oFrequencies = frequencyService.selectOFrequency(oFrequency);
                if(oFrequencies!=null){//如果为03 就是连个时辰的文件 0时 和12时
                    if(oFrequencies.getCode().equals("03")){*/
                        if(cpsjlx.equals("1")) {//判断cpsjlx 为0是世界时  未1是北京时,北京时要减去八小时
                            // 定义日期时间格式
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                            // 解析字符串为LocalDateTime对象
                            LocalDateTime dateTime = LocalDateTime.parse(getybtime, formatter);
                            // 减去8小时
                            LocalDateTime newDateTime = dateTime.minus(Duration.ofHours(8));
                            // 输出新的日期时间
                            mmap.addAttribute("qbsj", newDateTime.format(formatter));//起报时间
                        }else{//否则不减去八小时
                            mmap.addAttribute("qbsj", getybtime);//起报时间
                        }
                  /*  }
                }*/

            }
        }
        return prefix + "/yl";
    }
    @GetMapping("/yltar/{fileName}")
    public String yltar(@PathVariable("fileName") String file,ModelMap mmap){
        //判断是否为windows系统
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        String[] s = file.split("_");
        String filePath = "cloud/ocean"+"/"+s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3]+"/"+file;
        if(archive.equals("win")){
            filePath = "D:/cloud/ocean"+"/"+s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3]+"/"+file;
            //filePath = "D:/cloud/ocean/NMF/BEN/GO/GLDT/NCEP_BEN_GO_GLDT_2025010300_010d_ATM.tar";
        }else{//判断是否为linux系统

            //filePath = "/cloud/ocean"+"/"+s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3]+"/"+file;//正式环境用这个从根目录读取
            String pDir = configService.selectConfigByKey("gdlinuxpathh");//普通产品归档后路径
            filePath = pDir+"/"+s[0]+"/"+s[1]+"/"+s[2]+"/"+s[3]+"/"+file;//从项目当前目录读取
        }
        //获取起报时间和间隔时间
        mmap.addAttribute("filePath", filePath);
        return prefix + "/yltar";
    }

    /**
     * 展示压缩包中txt文件
     * @param filePath
     * @return
     */
    @PostMapping("/gettartxt")
    @ResponseBody
    public AjaxResult gettartxt(String filePath,String path){
        //判断是否为windows系统
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        try (InputStream is = Files.newInputStream(new File(filePath).toPath());
             TarArchiveInputStream tarInput = new TarArchiveInputStream(is)) {
            TarArchiveEntry entry;
            while ((entry = tarInput.getNextTarEntry()) != null) {
                System.out.println(entry.getName());
                if(entry.getName().equals(path)){
                    if (archive.equals("win")) {
                        String pDir = configService.selectConfigByKey("ncylwin");
                        long l = System.currentTimeMillis();
                        File outputFile = new File(pDir+"/", l+".txt");//输出到归档路径
                        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                            byte[] buffer = new byte[4096];
                            int len;
                            while ((len = tarInput.read(buffer)) != -1) {
                                fos.write(buffer, 0, len);
                            }
                     /*       //设置权限
                            Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rw-r--r--");
                            Files.setPosixFilePermissions(outputFile.toPath(), permissions);
                            System.out.println("文件权限已设置为rw-r--r--");*/
                            return AjaxResult.success(pDir+l+".txt");
                        }
                    } else {
                        String pDir = configService.selectConfigByKey("ncyllinux");
                        long l = System.currentTimeMillis();
                        File outputFile = new File(pDir+"/", l+".txt");//输出到归档路径
                        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                            byte[] buffer = new byte[4096];
                            int len;
                            while ((len = tarInput.read(buffer)) != -1) {
                                fos.write(buffer, 0, len);
                            }
                            //设置权限
                            Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rw-r--r--");
                            Files.setPosixFilePermissions(outputFile.toPath(), permissions);
                            System.out.println("文件权限已设置为rw-r--r--");
                        }
                        return AjaxResult.success(pDir+l+".txt");
                    }

                }
            }
            return AjaxResult.success("错误");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("/gettardata")
    @ResponseBody
    public AjaxResult gettardata(String filePath){
        try (InputStream is = Files.newInputStream(new File(filePath).toPath());
             TarArchiveInputStream tarInput = new TarArchiveInputStream(is)) {
            TarArchiveEntry entry;
            List<String> list = new ArrayList<>();
            while ((entry = tarInput.getNextTarEntry()) != null) {
                System.out.println(entry.getName());
                list.add(entry.getName());
                // 忽略目录条目
                /*if (entry.isDirectory()) {
                    continue;
                }*/
            }
            return AjaxResult.success(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 替换时间字符串中的小时部分
     *
     * @param timeString 原始时间字符串，格式为 "yyyy-MM-dd HH:mm:ss"
     * @param newHour    要替换成的新小时（0-23）
     * @return 更新后的时间字符串
     */
    public static String replaceHour(String timeString, int newHour) {
        // 确保新小时在有效范围内
        if (newHour < 0 || newHour > 23) {
            throw new IllegalArgumentException("Hour must be between 0 and 23");
        }

        // 格式化新小时为两位数字符串
        String newHourString = String.format("%02d", newHour);

        // 替换原始时间字符串中的小时部分
        return timeString.substring(0, 11) + newHourString + timeString.substring(13);
    }

    /**
     * 将字符串202102070800时间转换为yyyy-MM-dd HH:mm:ss
     * @param originalTimeString
     * @return
     */
    public String getybtime(String originalTimeString){
        // 原始时间字符串
        // 为了解析原始字符串，我们需要构建一个与之匹配的 SimpleDateFormat
        SimpleDateFormat originalFormatter = new SimpleDateFormat("yyyyMMddHHmm");
        // 用于格式化日期时间为所需格式的 SimpleDateFormat
        SimpleDateFormat targetFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 使用 originalFormatter 解析原始字符串为 Date 对象
            Date date = originalFormatter.parse(originalTimeString);
            // 使用 targetFormatter 将 Date 对象格式化为所需格式的字符串
            String formattedTimeString = targetFormatter.format(date);
            // 输出格式化后的时间字符串
            System.out.println("Formatted Time: " + formattedTimeString);
            return formattedTimeString;
        } catch (ParseException e) {
            // 如果解析过程中出现错误，则打印异常信息
            e.printStackTrace();
            return "-1";
        }
    }
/*    @GetMapping("/yltxt1")
    public String yltxt1(){
        return prefix + "/yltxt";
    }
    @GetMapping("/yl1/{fileName}")
    public String yltxt(@PathVariable("fileName") String fileName, ModelMap mmap){
        //mmap.addAttribute("yltxt",fileName);
        return prefix + "/yl1";
    }*/
@GetMapping("/getxz/{zxj}/{zxw}/{ysj}/{ysw}/{fileid}/{sx}")
@ResponseBody
public void getxz(@PathVariable("zxj") Double zxj, @PathVariable("zxw") Double zxw, @PathVariable("ysj") Double ysj, @PathVariable("ysw") Double ysw, @PathVariable("fileid") String fileid, @PathVariable("sx") String sx, HttpServletResponse response) throws IOException {
                ONcFile ncFile = ncFileService.selectONcFileById(fileid);
                if(ncFile != null) {//如果为查询到应该是智能网格产品
                    String targetFolderPath = ncFile.getFilePath();//ncFile.getFilePath()
                    String fileName = ncFile.getFileName();
                    //String cs = "D:\\cloud\\ocean\\NMF\\BEN\\OSMTSCA\\NWPACDT\\NMF_BEN_OSMWA_NWPACDT_2025011312_168h_WAVHs333.nc";
                    try (NetCDFSource source = new NetCDFSource(new File(targetFolderPath+"/"+fileName))) {//targetFolderPath+"/"+fileName
                        Date date = new Date();
                        String path = targetFolderPath + "cut_data/" + new SimpleDateFormat("yyyy年MM月dd日").format(date);
                        //String path = "D:\\cloud\\ocean\\NMF\\BEN\\OSMTSCA\\NWPACDTnccj\\2024年03月03日";
                        Path path1 = Paths.get(path);

                        // 检查文件夹是否存在
                        if (!Files.exists(path1)) {
                            try {
                                // 如果文件夹不存在，则尝试创建它
                                Files.createDirectories(path1);
                                System.out.println("文件夹已成功创建！");
                            } catch (IOException e) {
                                // 捕获并处理可能出现的 IOException
                                e.printStackTrace();
                                System.out.println("文件夹创建失败。");
                            }
                        }
                        //NetCDFSourceExtractor copier = new NetCDFSourceExtractor(source, path + ncFile.getFileName());
                        NetCDFSourceExtractor copier = new NetCDFSourceExtractor(source, path+"/"+ ncFile.getFileName());
                        LonLatBounds bounds = new LonLatBounds(zxj, ysj, zxw, ysw);
                        //LonLatBounds bounds = new LonLatBounds(115, 119, 33, 38);
                        //左下角x坐标minLon   左下角y坐标minLat     右上角x坐标maxLon   右上角y坐标maxLat
                        copier.extractzdy(bounds, null, sx);

                        // 根据文件路径创建File对象
                        File file = new File(path+"/"+ ncFile.getFileName());
                        // 检查文件是否存在
                        /*if (!file.exists()) {
                            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
                            return;
                        }*/
                        // 设置响应头
                        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                        response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
                        response.setContentLengthLong(file.length());

                        // 使用try-with-resources语句确保流会被关闭
                        try (InputStream inputStream = new FileInputStream(file);
                             OutputStream outputStream = response.getOutputStream()) {

                            // 创建一个缓冲区
                            byte[] buffer = new byte[2048];
                            int bytesRead;

                            // 从输入流中读取数据，并写入到输出流中
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }

                            // 刷新输出流，确保所有数据都被发送出去
                            outputStream.flush();
                        }
                    }
                }else{
                    if(isNumeric(fileid)) {//判断id是否都是数字，普通产品id不是数字只有智能网格id是数字
                        oNcfileMonitor nc = ncFileService.getncZnwgdata(Integer.parseInt(fileid));
                        String path1 = "";
                        //判断是否为win系统
                        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
                        if(archive.equals("win")){
                            String pDir = configService.selectConfigByKey("gdwinpathh");
                            path1 = pDir;
                        }else{//判断是否为linux系统
                            String pDir = configService.selectConfigByKey("gdlinuxpathh");
                            path1 = pDir;
                        }
                        String[] split = nc.getFilename().split("_");
                        String pq= path1+"/"+split[0]+"/"+split[1]+"/"+split[2]+"/"+split[3];
                        path1 = pq+"/"+nc.getFilename();

                        //String cs = "D:\\cloud\\ocean\\NMF\\BEN\\OSMTSCA\\NWPACDT\\NMF_BEN_OSMWA_NWPACDT_2025011312_168h_WAVHs333.nc";
                        try (NetCDFSource source = new NetCDFSource(new File(path1))) {//targetFolderPath+"/"+fileName
                            Date date = new Date();
                            String path = pq + "/cut_data/" + new SimpleDateFormat("yyyy年MM月dd日").format(date);
                            //String path = "D:\\cloud\\ocean\\NMF\\BEN\\OSMTSCA\\NWPACDTnccj\\2024年03月03日";
                            Path pathz = Paths.get(path);

                            // 检查文件夹是否存在
                            if (!Files.exists(pathz)) {
                                try {
                                    // 如果文件夹不存在，则尝试创建它
                                    Files.createDirectories(pathz);
                                    System.out.println("文件夹已成功创建！");
                                } catch (IOException e) {
                                    // 捕获并处理可能出现的 IOException
                                    e.printStackTrace();
                                    System.out.println("文件夹创建失败。");
                                }
                            }
                            //NetCDFSourceExtractor copier = new NetCDFSourceExtractor(source, path + ncFile.getFileName());
                            NetCDFSourceExtractor copier = new NetCDFSourceExtractor(source, path + "/" + nc.getFilename());
                            LonLatBounds bounds = new LonLatBounds(zxj, ysj, zxw, ysw);
                            //LonLatBounds bounds = new LonLatBounds(115, 119, 33, 38);
                            //左下角x坐标minLon   左下角y坐标minLat     右上角x坐标maxLon   右上角y坐标maxLat
                            copier.extractzdy(bounds, null, sx);

                            // 根据文件路径创建File对象
                            File file = new File(path + "/" +nc.getFilename());
                            // 检查文件是否存在
                        /*if (!file.exists()) {
                            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
                            return;
                        }*/
                            // 设置响应头
                            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                            response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
                            response.setContentLengthLong(file.length());

                            // 使用try-with-resources语句确保流会被关闭
                            try (InputStream inputStream = new FileInputStream(file);
                                 OutputStream outputStream = response.getOutputStream()) {

                                // 创建一个缓冲区
                                byte[] buffer = new byte[2048];
                                int bytesRead;

                                // 从输入流中读取数据，并写入到输出流中
                                while ((bytesRead = inputStream.read(buffer)) != -1) {
                                    outputStream.write(buffer, 0, bytesRead);
                                }

                                // 刷新输出流，确保所有数据都被发送出去
                                outputStream.flush();
                            }
                        }
                    }
                }

}

/*
    public static void main(String[] args) {
        // 设定你想要检查和创建的文件夹路径
        String directoryPath = "E:/22/2024年3月2日";

        // 调用 Paths.get() 方法，将路径字符串转换成 Path 对象
        Path path = Paths.get(directoryPath);

        // 检查文件夹是否存在
        if (!Files.exists(path)) {
            try {
                // 如果文件夹不存在，则尝试创建它
                Files.createDirectories(path);
                System.out.println("文件夹已成功创建！");
            } catch (IOException e) {
                // 捕获并处理可能出现的 IOException
                e.printStackTrace();
                System.out.println("文件夹创建失败。");
            }
        } else {
            System.out.println("文件夹已存在。");
        }
    }
*/

  /*  public static void main(String[] args) {
        getxz("1");
    }*/
    /**
     * 生成地图图片，备份方法getmappng1
     * @param sx 图层属性
     * @param wd 维度 时间维度 第几维度 int
     * @return
     */
    @PostMapping("/getmappng")
    @ResponseBody
    public AjaxResult getmappng(String path,String sx, int wd,String notCounting){
        File file = new File(path);//
        //判断是否为windows系统
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        int i = 0;
        try(NetCDFSource source= new NetCDFSource(file)) {
            //列出所有可用层
            NetcdfFile ncfile = source.getNcfile();
            String unitsString = "";
            for (Variable variable : ncfile.getVariables()) {
                String fullName = variable.getFullName();
                System.out.println(fullName);
                if(fullName.equals(sx)){
                    unitsString = variable.getUnitsString();
                    System.out.println(unitsString);
                }

            }

        /*    String unit = "---";
            for (NetCDFLayerBaseInfo netCDFLayerBaseInfo : source.listLayerBaseInfo()) {
                if(netCDFLayerBaseInfo.getName().equals(sx)){
                    unit = netCDFLayerBaseInfo.getSliceDimension().getUnit();
                }
            }*/

            NetCDFLayer layer = source.getLayer(sx);
            //DoubleRange layerValueRange1 = layer.getLayerValueRange(sx,Double.valueOf(notCounting));//方法有问题用下面这个
            DoubleRange layerValueRange = source.getLayerValueRange(sx, Float.parseFloat(notCounting),wd);//获取当前属性最大值最小值

            /**
             * 配置图片的颜色条图例颜色
             */
            Map map = new HashMap();
            ImmutableList<Dimension> getz = layer.getz();
            if(getz != null){
                if(getz.size() == 1){//如果等于1 证明有z字段
                    Dimension dimension = getz.get(0);
                    String name = dimension.getName();
                    Variable variable = ncfile.findVariable(name);
                    Array read = variable.read();
                    System.out.println(read);
                    map.put("z",read.toString());
                }
            }else{
                map.put("z",null);
            }
            double[] groups = divideRangeIntoGroups(layerValueRange.getMin(), layerValueRange.getMax(), 7);//后端配置的图例颜色共7种
            double[] groupsweb = divideRangeIntoGroups(layerValueRange.getMin(), layerValueRange.getMax(), 5);//返回前端配置的图例颜色共5种
            map.put("colors",groupsweb);
            map.put("unit",unitsString);
            MapRenderer mapRenderer = MapRenderer.create(layer);
            RasterLayerStyle style = createStyle(groups, Double.valueOf(notCounting));
            style.setClipRange(layerValueRange.getMin()-1,layerValueRange.getMax()+1);//在这个范围之外的数据都会是透明
            if (archive.equals("win")) {
                        String pDir = configService.selectConfigByKey("ncylwin");
                        long l = System.currentTimeMillis();
                        String s = pDir + "image" + l + ".png";
                        createFullImage(mapRenderer, wd,s,style);
                        return AjaxResult.success("/image" + l + ".png",map);
                    } else {
                        String pDir = configService.selectConfigByKey("ncyllinux");
                        String[] split = pDir.split("/");
                        long l = System.currentTimeMillis();
                        String s = pDir + "/image" + l + ".png";
                        createFullImage(mapRenderer, wd,s,style);
                        /*String[] split1 = pDir.split("/");*/
                        return AjaxResult.success("/image" + l + ".png",map);
                    }

             /*   }
            }*/
           // return AjaxResult.error();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InvalidRangeException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 下载获取属性进行裁剪
     * @param pid
     * @return
     * @throws Exception
     */
    @PostMapping("/getsxym")
    @ResponseBody
    public AjaxResult getsxym(String fileid){
        ONcFile ncFile = ncFileService.selectONcFileById(fileid);
        if(ncFile != null){//去普通产品里查询，如果查询不到就去智能网格产品中查询
            //String cs ="D:\\cloud\\ocean\\NMF\\BEN\\OSMTSCB\\NWPACDT\\NMF_BEN_OSMTSCB_NWPACDT_2025010712_168h_WL.nc";
            //String cs = "D:\\cloud\\ocean\\NMF\\BEN\\OSMTSCA\\NWPACDT\\NMF_BEN_OSMWA_NWPACDT_2025011312_168h_WAVHs333.nc";
            try(NetCDFSource source= new NetCDFSource(new File(ncFile.getFilePath()+"/"+ncFile.getFileName()))){//ncFile.getFilePath()//ncFile.getFilePath()+"/"+ncFile.getFileName()
                List<NetCDFLayerBaseInfo> layerInfos  = source.listLayerBaseInfo();
                if(layerInfos.size()==0){
                    return AjaxResult.error("未找到可显示图层!");
                }
                List<Map> list = new ArrayList<>();
                for (NetCDFLayerBaseInfo layerInfo : layerInfos) {
                    Map sx = new HashMap();//属性
                    String name = layerInfo.getName();
                    sx.put("name",name);
                    list.add(sx);
                }
                return AjaxResult.success(list);
            } catch (Exception e){
                return AjaxResult.error("1未找到可使用文件："+ncFile.getFilePath()+"/"+ncFile.getFileName());
            }
        }else{//获取智能网格数据
            if(isNumeric(fileid)){//判断id是否都是数字，普通产品id不是数字只有智能网格id是数字
                oNcfileMonitor nc= ncFileService.getncZnwgdata(Integer.parseInt(fileid));
                String path = "";
                //判断是否为win系统
                String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
                if(archive.equals("win")){
                    String pDir = configService.selectConfigByKey("gdwinpathh");
                    path = pDir;
                }else{//判断是否为linux系统
                    String pDir = configService.selectConfigByKey("gdlinuxpathh");
                    path = pDir;
                }
                String[] split = nc.getFilename().split("_");
                path = path+"/"+split[0]+"/"+split[1]+"/"+split[2]+"/"+split[3]+"/"+nc.getFilename();
                try(NetCDFSource source= new NetCDFSource(new File(path))){//ncFile.getFilePath()//ncFile.getFilePath()+"/"+ncFile.getFileName()
                    List<NetCDFLayerBaseInfo> layerInfos  = source.listLayerBaseInfo();
                    if(layerInfos.size()==0){
                        return AjaxResult.error("未找到可显示图层!");
                    }
                    List<Map> list = new ArrayList<>();
                    for (NetCDFLayerBaseInfo layerInfo : layerInfos) {
                        Map sx = new HashMap();//属性
                        String name = layerInfo.getName();
                        sx.put("name",name);
                        list.add(sx);
                    }
                    return AjaxResult.success(list);
                } catch (Exception e){
                    return AjaxResult.error("1未找到可使用文件："+ncFile.getFilePath()+"/"+ncFile.getFileName());
                }
            }
        }
        return AjaxResult.error("未找到文件");
    }
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]+");
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }
    @PostMapping("/getsx")
    @ResponseBody
    public AjaxResult getsx(String filePath) throws Exception{
        //String filename = "E:\\33.nc";
        try(NetCDFSource source= new NetCDFSource(new File(filePath))){
            List list = new ArrayList();
            //列出所有可用层
            List<NetCDFLayerBaseInfo> layerInfos  = source.listLayerBaseInfo();

            if(layerInfos.size()==0){
                return AjaxResult.error("未找到可显示图层!");
            }
            for (NetCDFLayerBaseInfo layerInfo : layerInfos) {
                Map sx = new HashMap();//属性
                Map data = new HashMap();//数据
                String name = layerInfo.getName();
                System.out.println("name="+name);
                List<List> list1 = new ArrayList<>();
                LonLatBounds  bounds= layerInfo.getBounds();
            /*    data.put("minLon",bounds.getMinLon());
                data.put("maxLon",bounds.getMaxLon());
                data.put("minLat",bounds.getMinLat());
                data.put("maxLat",bounds.getMaxLat());*/
                List<Double> list2 = new ArrayList<>();
                list2.add(bounds.getMinLat());
                list2.add(bounds.getMinLon());
                List<Double> list3 = new ArrayList<>();
                list3.add(bounds.getMaxLat());
                list3.add(bounds.getMaxLon());
                list1.add(list2);
                list1.add(list3);
                data.put("fw",list1);


                System.out.println("bounds:"+bounds);
                int sliceCount = 0;

                //显示时序维度信息
                NetCDFDimension sliceDimensionInfo = layerInfo.getSliceDimension();
                Object values = sliceDimensionInfo.getValues();
                if(sliceDimensionInfo !=null){
                    sliceCount = sliceDimensionInfo.getSize();
                    data.put("wd",values);
                    data.put("name",name);
                    data.put("unit",sliceDimensionInfo.getUnit());
                    System.out.println("sliceCount:"+sliceCount);
                    System.out.println("values:"+sliceDimensionInfo.getValues());
                    System.out.println("name:"+sliceDimensionInfo.getName());
                    System.out.println("unit:"+sliceDimensionInfo.getUnit());
                    System.out.println("desc:"+sliceDimensionInfo.getDescription());
                }
                sx.put("data",data);//添加属性
                list.add(sx);
                //NetCDFSource.isz();
            }

            return AjaxResult.success(list);
        }catch (Exception e){
            System.out.println(e);
            return AjaxResult.error("未找到文件目录：【"+filePath+"】");
        }
    }
    //备份上面的方法，上面的用于修改，改错可恢复下面方法把1去掉
    @PostMapping("/getsx1")
    @ResponseBody
    public List<String> getsx1(String filePath) throws Exception{
        String filename = filePath;
        NetcdfDataset dataset = NetcdfDatasets.openDataset(filename);
        ImmutableList<Variable> variables = dataset.getVariables();
        List<String> list = new ArrayList<>();
        for (int i = 0; i < variables.size(); i++) {
            Variable attributes = variables.get(i);
            list.add(attributes.getShortName());
        }
        return list;
    }

    /**
     * 为了解决kkfileview插件因文件名过长无法预览问题进行解决 将文件通过后台把文件复制放到别的文件夹并修改名称返回给预览插件
     */
    @PostMapping("/upisview")
    @ResponseBody
    public AjaxResult upisview(String filePath,String path,String hz)  {
        //查询文件夹下是否有预览文件，如果有循环删除
        //filePath = "D:\\cloud\\ocean\\NMF\\BEN\\OSM\\CSDT\\NMF_BEN_OSM_CSDT_2010122147_072h_SST.txt";
        //path = "D:\\cloud\\ocean\\NMF\\BEN\\OSM\\CSDT\\";
        File fileyvlan = new File(path);
        for (File file : fileyvlan.listFiles()) {
            boolean yl = file.getName().contains("yvlan");
            if(yl){
                //删除
                file.delete();
            }
        }
        //获取时间戳用于命名
        long timeStamp1 = System.currentTimeMillis();
        File file = new File(filePath);//传参的文件
        File file1 = new File(path+"/yvlan"+timeStamp1+"."+hz);//需要生成的预览文件
        String s = null;
        try {
                s = copyFileUsingFileStreams(file, file1, path+"/yvlan"+timeStamp1+"."+hz);
                //判断是否为doc文件，如果是doc文件，转为pdf文件预览
                if(hz.equals("doc")){//处理不兼容文件格式转其他类型
                    File oldFile = new File(path+"/yvlan"+timeStamp1+"."+hz);
                    File newFile = new File(path+"/yvlan"+timeStamp1+".pdf");
                    boolean renamed = oldFile.renameTo(newFile);
                    if(renamed){
                        return AjaxResult.success(path+"/yvlan"+timeStamp1+".pdf");
                    }else {
                        return AjaxResult.error("错误");
                    }
                }
            //判断是否为log文件，如果是log文件，转为doc文件预览
            if(hz.equals("log")){
                File oldFile = new File(path+"/yvlan"+timeStamp1+"."+hz);
                File newFile = new File(path+"/yvlan"+timeStamp1+".txt");
                boolean renamed = oldFile.renameTo(newFile);
                if(renamed){
                    return AjaxResult.success(path+"/yvlan"+timeStamp1+".txt");
                }else {
                    return AjaxResult.error("错误");
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return AjaxResult.success(s);
    }

    //public static void main(String[] args) {
        /*try {
            String html = "";
            Scanner scanner = new Scanner(new File("D:/file.txt"));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
               // System.out.println(line);
                html += line;
            }
            scanner.close();
            System.out.println(html);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
       /* StringBuilder fileContent = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(new FileReader("D:/file.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                fileContent.append(line).append("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String string = fileContent.toString();
        System.out.println(string);*/
    //}
    /**
     * 读取txt文件
     * @param
     * @return
     */
    @PostMapping("/txtview")
    @ResponseBody
    public AjaxResult txtview(String filePath) throws FileNotFoundException {
        StringBuilder fileContent = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                fileContent.append(line).append("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String string = fileContent.toString();
        System.out.println(string);
        return AjaxResult.success(string);
      /*  String html = "";
        try {
            Scanner scanner = new Scanner(new File(path));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
                html += line+"</br>";
            }
            scanner.close();
            System.out.println(html);
            return (html);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return (html);*/
    }
    private static String copyFileUsingFileStreams(File source, File dest,String path)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
        return path;
    }
    /*public static String copy(File oldfile, String newPath) {
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            int bytesum = 0;
            int byteread = 0;
            boolean exists = oldfile.exists();
            if (oldfile.exists()) {
                inStream = new FileInputStream(oldfile);
                fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }

            }
            return newPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
                if (fs != null) {
                    fs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return newPath;
    }*/
    /**
     * 读取NetCDF文件并生成GIF图片
     * @param filePath
     * @return
     * @throws IOException
     * @throws InvalidRangeException
     */
  /*  @PostMapping("/getmap")
    @ResponseBody*/
    public static String getmap(String filePath,String sx) throws IOException, InvalidRangeException {
        //判断是否为windows系统
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        // 打开 NetCDF 文件
        //测试文件路径
        //String filename = "E:\\33.nc";
        String filename = filePath;

        NetcdfDataset dataset = NetcdfDatasets.openDataset(filename);
        // 使用ImageIO获取所有GIF写入器
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("GIF");
        ImageWriter writer = writers.next();
        // 设置输出目标
        ImageOutputStream ios = null;
        if(archive.equals("win")) {
            ios = ImageIO.createImageOutputStream(new File("E:\\image.gif"));
        }else{
            ios = ImageIO.createImageOutputStream(new File("/home/image.gif"));
        }
        writer.setOutput(ios);
        writer.prepareWriteSequence(null);
        // 假设数据变量名为 "data"
        Variable dataVar = dataset.findVariable(sx);
        if (dataVar == null) {
            System.err.println("Data variable not found!");
            return null;
        }

        // 获取数据的维度
        int[] shape = dataVar.getShape();
        // 迭代时间维度（假设第一个维度是时间）
        for (int t = 0; t < shape[0]; t++) {
            // 读取二维切片数据
            Array read = dataVar.slice(0, t).read();
            int[] shape1 = read.getShape();
            float[][] slice = new float[shape1[0]][shape1[1]];
            for (int i = 0; i < shape1[0]; i++) {
                for (int j = 0; j < shape1[1]; j++) {
                    slice[i][j] = read.getFloat(i * shape1[1] + j);
                }
            }

            // 初始化最大值和最小值为数组中的第一个元素
            int max = 0;
            int min = 0;
            for (int i = 0; i < shape1[0]; i++) {
                for (int j = 0; j < shape1[1]; j++) {
                    int v = (int)slice[i][j];
                    if (v > max) {
                        max = v; // 更新最大值
                    }
                    if (v < min) {
                        if(v ==-9999){
                            //如果为-9999 不进行更改最小值
                        }else{
                            min = v; // 更新最小值
                        }

                    }
                }
            }
            // 生成图片
            BufferedImage image = new BufferedImage(shape1[1], shape1[0], BufferedImage.TYPE_INT_ARGB);

            for (int i = 0; i < shape1[0]; i++) {
                for (int j = 0; j < shape1[1]; j++) {
                    // 根据数据值设置颜色，这里是简单的灰度处理
                    int v = (int)slice[i][j];
                    Color color = getColor(v, min, max); // 假设数值范围是0到100
                    image.setRGB(j, i, color.getRGB());
                }
            }
            Graphics2D g2d = image.createGraphics();
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), image.getWidth(), 0, 0, image.getHeight(), null);
            g2d.dispose();
            BufferedImage bufferedImage = rotate180(image);
            // 保存图片
            // File outputFile = new File("E:\\image_" + t + ".png");
            // ImageIO.write(bufferedImage, "png", outputFile);
            IIOImage iioImage = new IIOImage(bufferedImage, null, null);
            writer.writeToSequence(iioImage, null);

        }
        System.out.println("图片生成成功！");
        // 关闭数据集
        dataset.close();
        //==================================
        // 文件路径
        File file = new File("E:\\image.gif");
        byte[] imageBytes = Files.readAllBytes(file.toPath());
        // 将图片字节数组进行 Base64 编码
        String base64EncodedImage = Base64Utils.encodeToString(imageBytes);

        // 返回 Base64 编码后的图片字符串
        return base64EncodedImage;
    }

    /**
     * 生成nc快试图单张图片
     * @param filePath
     * @param sx
     * @return
     * @throws IOException
     * @throws InvalidRangeException
     */
    @PostMapping("/getmappng1")
    @ResponseBody
    public String getmappng1(String filePath,String sx) throws IOException, InvalidRangeException {
        //判断是否为windows系统
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        // 打开 NetCDF 文件
        //测试文件路径
        //String filename = "E:\\33.nc";
        String filename = filePath;

        NetcdfDataset dataset = NetcdfDatasets.openDataset(filename);
        // 使用ImageIO获取所有GIF写入器
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("GIF");
        ImageWriter writer = writers.next();
        // 设置输出目标
        ImageOutputStream ios = null;
        if(archive.equals("win")) {
            String pDir = configService.selectConfigByKey("ncylwin");
            File folder = new File(pDir);
            // 如果文件夹不存在，则创建文件夹
            if (!folder.exists()) {
                if (folder.mkdirs()) {
                    System.out.println("文件夹创建成功：" + pDir);
                } else {
                   return "预览文件夹生成失败";
                }
            }
            ios = ImageIO.createImageOutputStream(new File(pDir+"image.gif"));
        }else{
            String pDir = configService.selectConfigByKey("ncyllinux");
            File folder = new File(pDir);
            // 如果文件夹不存在，则创建文件夹
            if (!folder.exists()) {
                if (folder.mkdirs()) {
                    System.out.println("文件夹创建成功：" + pDir);
                } else {
                    return "预览文件夹生成失败";
                }
            }
            ios = ImageIO.createImageOutputStream(new File(pDir+"image.gif"));
        }
        writer.setOutput(ios);
        writer.prepareWriteSequence(null);
        // 假设数据变量名为 "data"
        Variable dataVar = dataset.findVariable(sx);
        if (dataVar == null) {
            System.err.println("Data variable not found!");
            return null;
        }

        // 获取数据的维度
        //int[] shape = dataVar.getShape();
        // 迭代时间维度（假设第一个维度是时间）
        //for (int t = 0; t < shape[0]; t++) {
            // 读取二维切片数据
            Array read = dataVar.slice(0, 0).read();
            int[] shape1 = read.getShape();
            float[][] slice = new float[shape1[shape1.length-2]][shape1[shape1.length-1]];
            for (int i = 0; i < shape1[shape1.length-2]; i++) {
                for (int j = 0; j < shape1[shape1.length-1]; j++) {
                    slice[i][j] = read.getFloat(i * shape1[shape1.length-1] + j);
                }
            }

            // 初始化最大值和最小值为数组中的第一个元素
            int max = 0;
            int min = 0;
            for (int i = 0; i < shape1[shape1.length-2]; i++) {
                for (int j = 0; j < shape1[shape1.length-1]; j++) {
                    int v = (int)slice[i][j];
                    if (v > max) {
                        max = v; // 更新最大值
                    }
                    if (v < min) {
                        if(v ==-9999){
                            //如果为-9999 不进行更改最小值
                        }else{
                            min = v; // 更新最小值
                        }

                    }
                }
            }
            // 生成图片
            BufferedImage image = new BufferedImage(shape1[shape1.length-1], shape1[shape1.length-2], BufferedImage.TYPE_INT_ARGB);

            for (int i = 0; i < shape1[shape1.length-2]; i++) {
                for (int j = 0; j < shape1[shape1.length-1]; j++) {
                    // 根据数据值设置颜色，这里是简单的灰度处理
                    int v = (int)slice[i][j];
                    Color color = getColor(v, min, max); // 假设数值范围是0到100
                   // Color color1 = getColor(min, max, v);
                    image.setRGB(j, i, color.getRGB());
                }
            }
            Graphics2D g2d = image.createGraphics();
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), image.getWidth(), 0, 0, image.getHeight(), null);
            g2d.dispose();
            BufferedImage bufferedImage = rotate180(image);
            // 保存图片
            // File outputFile = new File("E:\\image_" + t + ".png");
            // ImageIO.write(bufferedImage, "png", outputFile);
            IIOImage iioImage = new IIOImage(bufferedImage, null, null);
            writer.writeToSequence(iioImage, null);

        //}
        System.out.println("图片生成成功！");
        // 关闭数据集
        dataset.close();
        //==================================
        // 文件路径
        String pathdz = "";
        if(archive.equals("win")) {
            String pDir = configService.selectConfigByKey("ncylwin");
            pathdz =pDir+"image.gif";
        }else{
            String pDir = configService.selectConfigByKey("ncyllinux");
            pathdz =pDir+"image.gif";
        }
        File file = new File(pathdz);
        byte[] imageBytes = Files.readAllBytes(file.toPath());
        // 将图片字节数组进行 Base64 编码
        String base64EncodedImage = Base64Utils.encodeToString(imageBytes);

        // 返回 Base64 编码后的图片字符串
        return base64EncodedImage;
    }

    static   MapRenderer renderer;
    private static RasterLayerStyle createStyle(double[] groups,double notCounting){


        RasterLayerStyle style = new RasterLayerStyle(notCounting);
        style.addStop(groups[0],new Color(0,0,255).getRGB());
        style.addStop(groups[1],new Color(28,129,233).getRGB());
        style.addStop(groups[2],new Color(245,219,75).getRGB());
        style.addStop(groups[3],new Color(243,219,75).getRGB());
        style.addStop(groups[4],new Color(223,143,36).getRGB());
        style.addStop(groups[5],new Color(214,85,47).getRGB());
        style.addStop(groups[6],new Color(255,0,0).getRGB());
        return style;
    }

    public static double[] divideRangeIntoGroups(double minValue, double maxValue, int numGroups) {
        minValue = getnum(minValue);
        maxValue = getnum(maxValue);
        double[] values = new double[numGroups];
        double step = (maxValue - minValue) / (numGroups - 1);

        for (int i = 0; i < numGroups; i++) {
            double v = minValue + i * step;

            values[i] =v;
        }

        return values;
    }
    public static double getnum(double n){
        String s = String.valueOf(n);
        if(s.contains("E") || s.contains("e")){
            String substring = s.substring(0, 6);
            Double v = Double.valueOf(substring);
            return v;
        }
        return n;
    }

    /**
     * 图片展示到地图上
     * @param req
     * @param resp
     * @throws IOException
     */
    public static void getMapRenderer() throws IOException {
        File file = new File("E:\\88.nc");


        try(NetCDFSource source= new NetCDFSource(file)){


            //列出所有可用层
            NcVariable ncVariable1 = new NcVariable();
            List<NetCDFLayerBaseInfo> layerInfos  = source.listLayerBaseInfo();
            for (NetCDFLayerBaseInfo layerInfo : layerInfos) {
                if(layerInfo.getName().equals("u")){
                    String name = layerInfo.getName();
                    System.out.println("name="+name);//属性 u v
                    LonLatBounds  bounds= layerInfo.getBounds();
                    System.out.println("bounds:"+bounds);//位置范围
                    int sliceCount = 0;

                    //显示时序维度信息
                    NetCDFDimension sliceDimensionInfo = layerInfo.getSliceDimension();
                    if(sliceDimensionInfo !=null){
                        sliceCount = sliceDimensionInfo.getSize();
                        System.out.println("sliceCount:"+sliceCount);//维度
                        System.out.println("values:"+sliceDimensionInfo.getValues());
                        System.out.println("name:"+sliceDimensionInfo.getName());
                        System.out.println("unit:"+sliceDimensionInfo.getUnit());//单位
                        System.out.println("desc:"+sliceDimensionInfo.getDescription());
                    }

                    NetCDFLayer layer =  source.getLayer(layerInfo.getName());
                    MapRenderer  mapRenderer =  MapRenderer.create(layer);

                    //显示多维度数据
                    DoubleRange layerValueRange = layer.getLayerValueRange(layerInfo.getName(),Double.valueOf("-9999"));//获取当前属性最大值最小值
                    /**
                     * 配置图片的颜色条图例颜色
                     */
                    double[] groups = divideRangeIntoGroups(layerValueRange.getMin(), layerValueRange.getMax(), 7);//后端配置的图例颜色共7种
                    //.....
                    if(sliceCount > 0){
                        for(int i = 0 ;i  < sliceCount  ; i ++){
                            createFullImage(mapRenderer,i,"C:\\tmp\\"  +System.currentTimeMillis() +"_"+name  +".png",createStyle(groups,-9999));
                        }
                    }
                    else {
                        createFullImage(mapRenderer,0,"C:\\tmp\\"  +System.currentTimeMillis() +"_"+name  +".png",createStyle(groups,-9999));
                    }
                }

            }
        }

    }

    private static void createFullImage(MapRenderer mapRenderer, int slice,String path,RasterLayerStyle style){
        byte[] tile = mapRenderer.getImage(slice,style,1.0);
        savePng(tile,path);
    }
    private static void savePng(byte[] data, String path){
        try {
            com.google.common.io.Files.write(data,new File(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
public static void uu(){
        String o = "NMF_BEN_OSMTSCA_NWPACDT_2024121512_168h_OCE.nc-02-no";
    String[] sj = o.split("-");
    //System.out.println(sj[sj.length-1]);
    if(sj[1].equals("no")){//判断时间间隔参数是否有值，没有值时间间隔按1进行设置
        System.out.println(1);//sjjg
    }else{
        System.out.println(sj[1]);//sjjg

    }
}
  /*  public static void main(String[] args) throws IOException {
        getMapRenderer();
        //uu();
    }*/
    public static void getMapRenderertest() throws IOException {
        /*File file = new File("E:\\33.nc");
        //判断是否为windows系统
        String archive = (String) YamlUtil.loadYaml("sysConfig.yaml").get("archive");
        int i = 0;
        try(NetCDFSource source= new NetCDFSource(file)){

            //列出所有可用层
            List<NetCDFLayerBaseInfo> layerInfos  = source.listLayerBaseInfo();
            for (NetCDFLayerBaseInfo layerInfo : layerInfos) {
                if(layerInfo.getName().equals("u")){
                    NetCDFLayer layer =  source.getLayer(layerInfo.getName());
                    MapRenderer  mapRenderer =  MapRenderer.create(layer);
                    if(archive.equals("win")) {
                        String pDir = configService.selectConfigByKey("ncylwin");
                        createFullImage(mapRenderer, i);
                    }else{
                        String pDir = configService.selectConfigByKey("ncyllinux");
                        createFullImage(mapRenderer, i);
                    }

                }
            }
        }*/

    }

    }

